package com.example.pclimb.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityRegisterBinding;
import com.example.pclimb.model.User;
import com.example.pclimb.repository.UserRepository;
import com.example.pclimb.viewmodel.UserViewModel;

/**
 * 注册页面
 */
public class RegisterActivity extends AppCompatActivity {

    private ActivityRegisterBinding binding;
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 设置注册按钮点击事件
        binding.btnRegister.setOnClickListener(v -> attemptRegister());

        // 设置登录提示点击事件
        binding.tvLoginPrompt.setOnClickListener(v -> {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        });
    }

    /**
     * 尝试注册
     */
    private void attemptRegister() {
        // 重置错误提示
        binding.tilUsername.setError(null);
        binding.tilPassword.setError(null);
        binding.tilConfirmPassword.setError(null);
        binding.tilPhone.setError(null);
        binding.tilEmail.setError(null);

        // 获取输入值
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();
        String confirmPassword = binding.etConfirmPassword.getText().toString().trim();
        String phone = binding.etPhone.getText().toString().trim();
        String email = binding.etEmail.getText().toString().trim();
        int userType = 0; // 默认为普通用户

        // 验证输入
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(username)) {
            binding.tilUsername.setError(getString(R.string.error_field_required));
            focusView = binding.etUsername;
            cancel = true;
        }

        if (TextUtils.isEmpty(password)) {
            binding.tilPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etPassword;
            cancel = true;
        } else if (password.length() < 6) {
            binding.tilPassword.setError(getString(R.string.error_password_too_short));
            focusView = binding.etPassword;
            cancel = true;
        }

        if (TextUtils.isEmpty(confirmPassword)) {
            binding.tilConfirmPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etConfirmPassword;
            cancel = true;
        } else if (!password.equals(confirmPassword)) {
            binding.tilConfirmPassword.setError(getString(R.string.error_passwords_not_match));
            focusView = binding.etConfirmPassword;
            cancel = true;
        }

        if (TextUtils.isEmpty(phone)) {
            binding.tilPhone.setError(getString(R.string.error_field_required));
            focusView = binding.etPhone;
            cancel = true;
        }

        if (TextUtils.isEmpty(email)) {
            binding.tilEmail.setError(getString(R.string.error_field_required));
            focusView = binding.etEmail;
            cancel = true;
        } else if (!isEmailValid(email)) {
            binding.tilEmail.setError(getString(R.string.error_invalid_email));
            focusView = binding.etEmail;
            cancel = true;
        }

        if (cancel) {
            // 输入有误，聚焦到错误输入框
            focusView.requestFocus();
        } else {
            // 显示进度条，执行注册
            showProgress(true);

            // 检查用户名是否已存在
            userViewModel.getUserByUsername(username).observe(this, existingUser -> {
                if (existingUser != null) {
                    // 用户名已存在
                    showProgress(false);
                    binding.tilUsername.setError(getString(R.string.error_username_exists));
                    binding.etUsername.requestFocus();
                } else {
                    // 创建用户对象
                    User user = new User(username, password, phone, email, userType);
                    user.setNickname(username); // 默认使用用户名作为昵称

                    // 执行注册
                    userViewModel.insert(user, new UserRepository.Callback<Long>() {
                        @Override
                        public void onResult(Long result) {
                            runOnUiThread(() -> {
                                showProgress(false);
                                if (result > 0) {
                                    // 注册成功
                                    Toast.makeText(RegisterActivity.this, R.string.register_success, Toast.LENGTH_SHORT).show();
                                    // 跳转到登录页面
                                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    // 注册失败
                                    Toast.makeText(RegisterActivity.this, R.string.register_failure, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                }
            });
        }
    }

    /**
     * 验证邮箱格式
     */
    private boolean isEmailValid(String email) {
        return email.contains("@") && email.contains(".");
    }

    /**
     * 显示或隐藏进度条
     */
    private void showProgress(boolean show) {
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.btnRegister.setEnabled(!show);
        binding.etUsername.setEnabled(!show);
        binding.etPassword.setEnabled(!show);
        binding.etConfirmPassword.setEnabled(!show);
        binding.etPhone.setEnabled(!show);
        binding.etEmail.setEnabled(!show);
    }
} 